<template>
  <div class="page-content feedback-detail">
    <el-skeleton :loading="isLoading" animated>
      <template #template>
        <div class="skeleton-container">
          <div class="flex justify-between items-center mb-6">
            <el-skeleton-item variant="text" style="width: 200px; height: 32px" />
            <el-skeleton-item variant="button" style="width: 100px; height: 40px" />
          </div>
          <el-skeleton-item variant="p" style="width: 100%; height: 80px" />
          <div class="flex mt-4">
            <el-skeleton-item
              variant="image"
              style="width: 80px; height: 80px; margin-right: 10px"
            />
            <el-skeleton-item variant="image" style="width: 80px; height: 80px" />
          </div>
          <el-skeleton-item variant="p" style="width: 100%; height: 200px; margin-top: 20px" />
        </div>
      </template>

      <template #default>
        <!-- 页面标题和操作按钮 -->
        <div class="mb-6 flex justify-between items-center">
          <div>
            <h1 class="text-2xl font-bold">反馈详情</h1>
            <p class="text-gray-500 mt-2">查看并处理用户提交的反馈信息</p>
          </div>
          <div class="flex gap-2">
            <el-button @click="goBack" class="ml-auto">
              <el-icon><Back /></el-icon>返回
            </el-button>
          </div>
        </div>

        <!-- 反馈信息卡片 -->
        <el-card shadow="hover" class="mb-6">
          <div class="feedback-header flex justify-between items-start">
            <div class="flex items-center">
              <div>
                <div class="text-gray-500 text-sm mt-1"
                  >联系方式: {{ feedback.contactWay || '未提供' }}</div
                >
              </div>
            </div>
            <div class="flex flex-col items-end">
              <el-tag :type="getFeedbackTypeColor( FeedbackTypeMaps[parseInt(feedback.type) - 1])
              " effect="light" class="mb-2">
                {{ FeedbackTypeMaps[parseInt(feedback.type) - 1] }}
              </el-tag>
                <el-tag :type="getFeedbackStatusColor(FeedbackStatusMaps[parseInt(feedback.state) - 1])" effect="light">
                  {{ FeedbackStatusMaps[parseInt(feedback.state) - 1] }}
              </el-tag>
              <div class="text-gray-500 text-sm mt-2">
                提交时间: {{feedback.createTime ? useDateFormat(feedback.createTime, 'YYYY/MM/DD HH:mm:ss') : '' }}
              </div>
            </div>
          </div>

          <div class="feedback-content mt-6">
            <div class="text-gray-700">
              {{ feedback.content }}
            </div>
            <!-- 图片预览 -->
            <div
              v-if="fileList && fileList.length > 0"
              class="image-container mt-4 flex flex-wrap gap-2"
            >
              <el-image
                v-for="(img, index) in fileList"
                :key="index"
                :src="img"
                :preview-src-list="fileList"
                :initial-index="index"
                fit="cover"
                class="rounded"
                style="width: 120px; height: 120px"
              >
                <template #error>
                  <div class="flex justify-center items-center h-full bg-gray-100">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </div>
        </el-card>
        <!-- 回复和处理卡片 -->
        <el-card shadow="hover" class="reply-card">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="font-medium">回复与处理</span>
              <div>
                <el-button
                  v-if="feedback.state == 1"
                  type="success"
                  size="small"
                  @click="handleProcess(2)"
                >
                  <el-icon><Setting /></el-icon>开始处理
                </el-button>
                <el-button
                  v-if="feedback.state == 3"
                  type="info"
                  size="small"
                  @click="handleProcess(4)"
                >
                  <el-icon><CircleCheck /></el-icon>结束处理
                </el-button>
              </div>
            </div>
          </template>

          <!-- 管理员回复 -->
          <div v-if="feedback.adminReply" class="admin-reply bg-blue-50 p-4 rounded-lg mb-6">
            <div class="flex justify-between items-start">
              <div class="flex items-center">
                <el-avatar :size="40" class="mr-3 bg-blue-500">管理员</el-avatar>
                <div>
                  <div class="font-medium">管理员回复</div>
                  <div class="text-xs text-gray-500 mt-1">{{
                    feedback.updateTime ? formatDateTime(feedback.updateTime) : ''
                  }}</div>
                </div>
              </div>
            </div>
            <div class="mt-3 text-gray-700">
              {{ feedback.adminReply }}
            </div>
          </div>

          <!-- 回复表单 -->
          <div v-if="feedback.state != 4" >
            <h3 class="text-lg font-medium mb-4">{{
              feedback.adminReply ? '更新回复' : '添加回复'
            }}</h3>
            <el-form :model="replyForm" label-position="top">
              <el-form-item label="回复内容">
                <el-input
                  v-model="replyForm.reply"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入回复内容"
                />
              </el-form-item>
              <!-- <el-form-item label="处理状态">
                <el-select v-model="replyForm.status" placeholder="请选择状态" style="width: 100%" disabled>
                  <el-option
                    v-for="(value, key,index) in FeedbackStatusEnum"
                    :key="key"
                    :label="value"
                    :value="index"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" @click="submitReply">提交回复</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div v-else class="bg-gray-50 p-4 rounded text-center text-gray-500">
            该反馈已关闭，无法继续回复
          </div>
        </el-card>

        <!-- 处理日志 -->
        <el-card shadow="hover" class="mt-6">
          <template #header>
            <div class="flex justify-between items-center">
              <span class="font-medium">处理记录</span>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in activityTimeline"
              :key="index"
              :timestamp="useDateFormat(activity.createTime, 'YYYY/MM/DD HH:mm:ss').value"
              :type:any="activity.type"
              :hollow="activity.hollow"
              :color="activity.color"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </template>
    </el-skeleton>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useDateFormat } from '@vueuse/core'
  import { useWorktabStore } from '@/store/modules/worktab'
  import { FeedbackTypeEnum, FeedbackStatusEnum } from '@/types/feedback'
  import {
    scenicComplaintFeedbackGetComplaintFeedbackByIdUsingGet,
    scenicComplaintFeedbackDisposeSaveFeedbackDisposeUsingPost,
    scenicComplaintFeedbackDisposeUpdateFeedbackDisposeUsingPut
    } from '@/api/4a'

  const route = useRoute()
  const router = useRouter()
  const feedbackId = ref(route.query.id ? route.query.id : undefined)
  const isLoading = ref(true)
  const fileList = ref([])
  // 反馈详情数据
  const feedback = ref<any>({
    id: 0,
    userId: 0,
    userName: '',
    type: '',
    content: '',
    status: '',
    createTime: ''
  })
    // 反馈类型
    const FeedbackTypeMaps = Object.keys(FeedbackTypeEnum).map(
        (key) => FeedbackTypeEnum[key as keyof typeof FeedbackTypeEnum]
    )

    // 状态类型
    const FeedbackStatusMaps = Object.keys(FeedbackStatusEnum).map(
        (key) => FeedbackStatusEnum[key as keyof typeof FeedbackStatusEnum]
    )
  // 回复表单数据
  const replyForm = reactive({
    reply: '',
    status: 'REPLIED'
  })

  // 活动记录
  const activityTimeline = ref([
    {
      content: '用户提交反馈',
      createTime: '',
      type: 'primary',
      hollow: false,
      color: '#409EFF'
    }
  ])

  // 获取反馈类型颜色
  const getFeedbackTypeColor = (type: string) => {
    switch (type) {
      case FeedbackTypeEnum.BUG:
        return 'danger'
      case FeedbackTypeEnum.SUGGESTION:
        return 'success'
      case FeedbackTypeEnum.COMPLAINT:
        return 'warning'
      case FeedbackTypeEnum.QUESTION:
        return 'info'
      default:
        return undefined
    }
  }

  // 获取反馈状态颜色
  const getFeedbackStatusColor = (status: string) => {
    switch (status) {
      case FeedbackStatusEnum.PENDING:
        return 'danger'
      case FeedbackStatusEnum.PROCESSING:
        return 'warning'
      case FeedbackStatusEnum.REPLIED:
        return 'success'
      case FeedbackStatusEnum.CLOSED:
        return 'info'
      default:
        return undefined
    }
  }

  // 格式化日期时间
  const formatDateTime = (dateStr?: string) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleString()
  }

  // 获取反馈详情
  const fetchFeedbackDetail = async () => {
    if (!feedbackId.value) {
      ElMessage.error('反馈ID不能为空')
      router.push('/feedback/FeedbackList')
      return
    }
    isLoading.value = true
    try {
      const res: any = await scenicComplaintFeedbackGetComplaintFeedbackByIdUsingGet({params:{id:feedbackId.value as any}})
      if (res.code == 0) {
        Object.assign(feedback.value, res.data)
        fileList.value = feedback.value.file ? feedback.value.file.split(',').map((item: string) => item.trim()) : []
        replyForm.status = feedback.value.state
        updateActivityTimeline('detail')
      isLoading.value = false
      } else {
        ElMessage.error('获取反馈详情失败')
        router.push('/feedback/FeedbackList')
      }
    } 
    catch (error) {
      ElMessage.error('获取反馈详情失败')
      isLoading.value = false
      router.push('/feedback/FeedbackList')
    }
  }

  // 更新活动记录
  const updateActivityTimeline = (data?: any) => {
    if(data == 'detail'){
      activityTimeline.value = feedback.value.complaintFeedbackDisposeContent || []
    }
    
    if(data == 'reply'){
      activityTimeline.value.push({
      createTime:feedback.value.updateTime,
      content:feedback.value.adminReply,
      type:'',
      hollow:false,
      color:''
    })
    } 
  }

  // 开始处理
  const handleProcess = (val:number) => {
    ElMessageBox.confirm('确认开始处理该反馈?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        let body = {
            ...feedback.value,
            state: val,
            feedbackId:feedback.value.id,
            current: 1,
            size: 10,
        }
        scenicComplaintFeedbackDisposeUpdateFeedbackDisposeUsingPut({ body })
            .then((res: any) => {
                if (res.code === 0) {
                    feedback.value.state =val
                    feedback.value.updateTime = new Date().toISOString()
                    updateActivityTimeline()
                    ElMessage.success('状态已更新完成')
                } else {
                    ElMessage.error(res.msg)
                }
            })
            .catch((error) => {
                ElMessage.error(error || '处理失败，请稍后重试')
            })
        })
      .catch(() => {})
  }

  // 提交回复
  const submitReply = () => {
    if (!replyForm.reply.trim()) {
      ElMessage.warning('请输入回复内容')
      return
    }
        let body = {
            ...feedback.value,
            feedbackId: feedback.value.id,
            content:replyForm.reply,
            state:3,
            current: 1,
            size: 10
        }
        // 调用接口
        scenicComplaintFeedbackDisposeSaveFeedbackDisposeUsingPost({ body }).then((res: any) => {
            if (res.code == 0) {
                feedback.value.adminReply = replyForm.reply
                feedback.value.status =
                  FeedbackStatusEnum[replyForm.status as keyof typeof FeedbackStatusEnum]
                feedback.value.updateTime = new Date().toISOString()
                feedback.value.state = 3
                updateActivityTimeline('reply')
                ElMessage.success('回复成功')
            } else {
                ElMessage.error(res.msg)
            }
        })
   
  }

  // 返回列表
  const goBack = () => {
    const worktabStore = useWorktabStore()
    worktabStore.removeTab(route.path)
    router.push('/feedback/FeedbackList')
  }

  onMounted(() => {
    fetchFeedbackDetail()
  })
</script>

<style lang="scss" scoped>
  .feedback-detail {
    .feedback-content {
      word-break: break-word;
    }

    .admin-reply {
      background-color: rgba(64, 158, 255, 0.1);
      border-left: 4px solid var(--el-color-primary);
    }
  }
</style>
